package cn.tedu.sp11.fallback;

import com.tedu.web.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Component
public class ItemFB implements FallbackProvider {

   //返回一个service id，针对指定的服务进行降级处理
    //如果返回* 或null，则是对 所有服务都应用这个降级类
    @Override
    public String getRoute() {
        return "item-service";
    }

    //降级响应，返回一个封装响应数据的 response对象
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {

       return new ClientHttpResponse() {
           @Override
           public HttpStatus getStatusCode() throws IOException {
               return HttpStatus.OK;
           }

           @Override
           public int getRawStatusCode() throws IOException {
               return HttpStatus.OK.value();
           }

           @Override
           public String getStatusText() throws IOException {
               return HttpStatus.OK.getReasonPhrase();
           }

           @Override
           public void close() {

           }

           @Override
           public InputStream getBody() throws IOException {
                //JsonResult {code:401,msg:商品调用服务失败，data:null}
               String json= JsonResult.err().msg("调用商品服务失败").toString();
               return new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
           }

           @Override
           public HttpHeaders getHeaders() {
               //Content-Type:application/json;charset=UTF-8
               HttpHeaders h=new HttpHeaders();
               h.add("Content-Type","application/json;charset=UTF-8");
               return h;
           }
       };


    }
}
